


//
//  YYYComposeController.swift
//  HotNews
//
//  Created by YYY on 2017/11/3.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit
import SVProgressHUD

class YYYComposeController: UIViewController {

    //设置文本的输入视图
    private lazy var emoticonView = EmoticonInputView()
    
    //定义回调闭包
    private var selectedEmoticonCallBack: ((_ em: YYYEmoticonModel?)->())?
    
    //设置标题
    private lazy var composeTitle = UILabel(frame: CGRect(origin: CGPoint(), size: CGSize(width: 100, height: 30)))
    
    //导航栏右边按钮
    private lazy var sendButton: UIButton = {
        let btn = UIButton(title: "发布", fontSize: 15, normalColor: UIColor.white, backgroundImageName: nil)
        //设置不可用
        btn.isEnabled = false
        btn.frame.size = CGSize(width: 45, height: 35)
        btn.addTarget(self, action: #selector(sendAction), for: .touchUpInside)
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        //高亮背景图片
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        
        return btn
    }()
    //文本视图
    private lazy var composeTextView = YYYComposeTextView(frame: CGRect(x: 0, y: 0, width: kDeviceWidth, height: kDeviceHeight-44), textContainer: nil)
    //底部工具栏
    private lazy var toolBar = UIToolbar(frame: CGRect(x: 0, y: kDeviceHeight-44, width: kDeviceWidth, height: 44))
    
    override func viewDidLoad()
    {
        super.viewDidLoad()
        
        selectedEmoticonCallBack = { [weak self] (em) in
            self?.composeTextView.insertEmoticon(em: em)
        }
        //注册监听者
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //初始化控件
        setupUI()
        //设置代理
        composeTextView.delegate = self
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //显示键盘
        composeTextView.becomeFirstResponder()
    }
    
    override func viewWillDisappear(_ animated: Bool)
    {
        super.viewWillDisappear(animated)
        //隐藏键盘
        composeTextView.resignFirstResponder()
    }

    //移除监听键盘frame的通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    //键盘变化的通知
    @objc private func keyboardWillChangeFrame(n: Notification)
    {
        guard let userInfo = n.userInfo
               else
        {
            return
        }
        let rect = (userInfo["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        //动画持续时间
        let duration = (userInfo["UIKeyboardAnimationDurationUserInfoKey"] as! NSNumber).doubleValue
        //添加动画
        let newBottom = view.height - rect.size.height

        UIView.animate(withDuration: duration) {
            self.toolBar.setBottom(newBottom: newBottom)
        }
    }
    //关闭
    @objc private func close()
    {
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
    }
    
    //切换表情键盘
    @objc private func emoticonKeyboard()
    {
        //如果使用系统默认的键盘，文本视图的inputView为nil，可以进行自定义
        composeTextView.inputView = (composeTextView.inputView == nil) ? emoticonView : nil
        emoticonView.selectedEmoticonCallBack = selectedEmoticonCallBack
        
        //刷新表情键盘
        composeTextView.reloadInputViews()
    }
    //发布微博
    @objc private func sendAction()
    {
        let text = composeTextView.emoticonText
        let image: UIImage? = UIImage(named: "d_aini")
        YYYNetworkManager.shared.postStatus(text: text, image: image) { (json, isSuccess) in

            //修改指示器样式
            SVProgressHUD.setDefaultStyle(.dark)
            let message = isSuccess ? "发布成功" : "网络不给力"
            SVProgressHUD.show(withStatus: message)
            if isSuccess
            {
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1)
                {
                    SVProgressHUD.setDefaultStyle(.light)
                    self.close()
                    return
                }
            }
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1)
            {
                SVProgressHUD.setDefaultStyle(.light)
                self.close()
            }
        }
    }
}

// MARK: UITextViewDelegate
extension YYYComposeController: UITextViewDelegate
{
    func textViewDidChange(_ textView: UITextView) {
        sendButton.isEnabled = composeTextView.hasText
    }
}
extension YYYComposeController
{
    //初始化控件
    func setupUI()
    {
        //文本视图
        view.addSubview(composeTextView)

        //底部工具栏
        view.addSubview(toolBar)
        //设置导航栏
        setupNavigationBar()
        //设置底部工具栏
        setupToolBar()
    }
    //设置导航栏
    func setupNavigationBar()
    {
        //导航栏左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", fontSize: 14, target: self, action: #selector(close), isBack: false)
        //设置标题
        let dict = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 14),
                    NSAttributedStringKey.foregroundColor: UIColor.darkGray]
        
        let screen_name = YYYNetworkManager.shared.userAccount.screen_name ?? ""
        
        let attributed = NSMutableAttributedString(string: screen_name, attributes: dict)
        
        composeTitle.attributedText = attributed
        
        navigationItem.titleView = composeTitle
        //导航栏右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
    }
    
    //设置底部工具栏
    func setupToolBar()
    {
        //items数组
        var items = [UIBarButtonItem]()
        let itemPictureArray = [["imageName": "compose_toolbar_picture"],
                                ["imageName": "compose_mentionbutton_background"],
                                ["imageName": "compose_trendbutton_background"],
                                ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
                                ["imageName": "compose_add_background"]
        ]
        for dict in itemPictureArray
        {
            let itemButton = UIButton()
            
            guard let imageName = dict["imageName"] else
            {
                continue
            }
            let actionName = dict["actionName"]
            if let actionName = actionName
            {
                itemButton.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            let imageNormal = UIImage(named: imageName)
            let imageHighlighted = UIImage(named: imageName + "_highlighted")
            itemButton.setImage(imageNormal, for: .normal)
            itemButton.setImage(imageHighlighted, for: .highlighted)
            itemButton.sizeToFit()
            items.append(UIBarButtonItem(customView: itemButton))
            //增加弹簧间距
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
        
    }
}
